﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace Lynn.Infastructure.Net.Http
{
    public class SSL
    {
        /// <summary>
        /// 证书密码
        /// </summary>
        public string Pwd { get; set; }
        /// <summary>
        /// 证书相对目录
        /// </summary>
        public string Path { get; set; }
        internal X509Certificate2 Cert
        {
            get
            {
                if (_cert == null)
                {
                    _cert = FindCert();
                }
                return _cert;
            }
        }
        private X509Certificate2 _cert { get; set; }
        private X509Certificate2 FindCert()
        {
            ////证书
            var path = AppDomain.CurrentDomain.BaseDirectory + Path;
            var certLoad = new X509Certificate2(path, Pwd);
            var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            if (isWindows)
            {
                //在个人区根据指纹查找证书
                var store = new X509Store("MY", StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                var cert = store.Certificates.Find(X509FindType.FindByThumbprint, certLoad.Thumbprint, false)[0];
                return cert == null ? certLoad : cert;
            }
            return certLoad;
        }
    }
}
